<template>
  <div>
    <van-search
      v-model="serchStr"
      show-action
      placeholder="请输入镜像关键词"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <div v-if="imageList">
      <ul class="list">
        <li>
          <span>名字</span>
          <span>Star</span>
          <span class="btn">操作</span>
        </li>
        <li v-for="item in randerList" :key="item.Id">
          <span>{{item.name}}</span>
          <span>{{item.star_count}}</span>
          <span class="btn"><van-button size="mini" @click="pullImage(item.name)" type="info">拉取</van-button></span>
        </li>
      </ul>
      <van-pagination
        v-model="currentPage"
        :total-items="imageList.length"
        :show-page-size="pageNum"
        force-ellipses
        class="page"
      />
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { Search, Button, Pagination } from 'vant'

Vue.use(Search)
Vue.use(Button)
Vue.use(Pagination)
export default {
  data () {
    return {
      currentPage: 1,
      serchStr: '',
      imageList: null,
      randerList: null,
      pageNum: 10
    }
  },
  watch: {
    // 监听分页
    currentPage: function () {
      this.jisuanImage()
    }
  },
  methods: {
    // 拉取镜像
    pullImage (name) {
      const parse = {
        data: {
          docker: `curl --unix-socket /var/run/docker.sock -s -X POST "http:/v1.40/images/create?fromImage=${name}:latest"`
        }
      }
      this.$post(parse, res => {
        this.$Notify({ type: 'success', message: '镜像拉取成功！' })
        this.$router.go(-1)
      })
    },
    // 搜索镜像
    onSearch () {
      const parse = {
        data: {
          docker: `curl --unix-socket /var/run/docker.sock -s "http:/v1.40/images/search?term=${this.serchStr}"`
        }
      }
      this.$post(parse, res => {
        this.imageList = JSON.parse(res)
        this.jisuanImage()
      })
    },
    // 计算当前页面显示
    jisuanImage () {
      this.randerList = this.imageList.slice(((this.currentPage - 1) * this.pageNum), this.currentPage * this.pageNum)
    }
  }
}
</script>

<style lang="scss" scope>
.page{
  margin-top: vw(20);
}
.list{
  margin-top: vw(10);
  li{
    line-height: vw(75);
    display: flex;
    span{
      flex: 1;
      padding: auto vw(20);
      overflow: hidden; //超出部分隐藏
      text-overflow: ellipsis; //超出部分显示...
      white-space: nowrap; //文本强制一行显示
      &:nth-child(1){
        padding: 0 vw(10);
      }
      &:nth-child(2){
        flex: .5;
        text-align: center;
      }
    }
    .btn{
      flex: .4;
      text-align: center;
    }
    &:nth-child(2n-1){
      background: #F7FCFF;
    }
    &:nth-child(1){
      background: #f2f2f2;
    }
  }
}
</style>
